from flask import Flask, request, render_template
from flask_cors import *
import threading
import datetime
import subprocess
import schedule
import os

SERVER_IP = (
    os.getenv("SERVER_IP") if os.getenv("SERVER_IP") is not None else "127.0.0.1"
)
SERVER_PORT = (
    os.getenv("SERVER_PORT") if os.getenv("SERVER_PORT") is not None else "5555"
)
RTMP_PORT = os.getenv("RTMP_PORT") if os.getenv("RTMP_PORT") is not None else "1935"
INNER_PORT = 5555

socket_num = 0
rtsp_process = {}
rtsp_count = {}
rtsp_time = {}
wait_time = 5

app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route("/")
def index():
    return "Hello world!"


"""
rtsp转hls相关接口
"""


@app.route("/rtspToHlsOn", methods=["GET"])
def rtsp_hls_on():
    ip = request.args.get("ip")
    ip_channel = get_ip_channel(ip)
    ip_tag = ip_channel + "_hls"

    saveadd = "hls/{0}.m3u8".format(ip_channel)
    transadd = "http://{0}:{1}/{2}".format(SERVER_IP, SERVER_PORT, saveadd)

    if ip_tag in rtsp_process:
        rtsp_count[ip_tag] += 1
    else:
        command = "ffmpeg -rtsp_transport tcp -i {0} -strict -2 -c:v libx264 -vsync 2 -c:a aac -f hls -hls_time 3 -hls_list_size 5 -hls_wrap 10 /tmp/{1}".format(
            ip, saveadd
        )
        print(command)
        rtsp_process[ip_tag] = subprocess.Popen(command.split(" "))
        rtsp_count[ip_tag] = 1

    rtsp_time[ip_tag] = datetime.datetime.now() + datetime.timedelta(
        minutes=wait_time
    )
    return transadd


@app.route("/rtspToHlsOff", methods=["GET"])
def rtsp_hls_off():
    ip = request.args.get("ip")
    ip_tag = get_ip_channel(ip) + "_hls"

    if ip_tag not in rtsp_process:
        return "-1"
    else:
        rtsp_count[ip_tag] -= 1
        if rtsp_count[ip_tag] <= 0:
            rtsp_process[ip_tag].kill()
            del rtsp_process[ip_tag]
            del rtsp_time[ip_tag]
            del rtsp_count[ip_tag]

    if ip_tag in rtsp_count:
        res = str(rtsp_count[ip_tag])
    else:
        res = "0"
    return res


@app.route("/rtspToHlsContinue", methods=["GET"])
def rtsp_hls_continue():
    ip = request.args.get("ip")
    ip_tag = get_ip_channel(ip) + "_hls"

    if ip_tag not in rtsp_process:
        return "-1"
    else:
        rtsp_time[ip_tag] = datetime.datetime.now() + datetime.timedelta(
            minutes=wait_time
        )
    return str(rtsp_time[ip_tag])


"""
rtsp转rtmp相关接口
"""


@app.route("/rtspToRtmpOn", methods=["GET"])
def rtsp_rtmp_on():
    ip = request.args.get("ip")
    ip_channel = get_ip_channel(ip)
    ip_tag = ip_channel + "_rtmp"

    rtaddr = "rtmp://{0}:{1}/live/room_{2}".format(SERVER_IP, RTMP_PORT, ip_channel)

    if ip_tag in rtsp_process:
        rtsp_count[ip_tag] += 1
    else:
        command = "ffmpeg -rtsp_transport tcp -i {0} -f flv -r 15 -s 640x480 -b:v 1000k -an {1}".format(
            ip, rtaddr
        )
        print(command)
        rtsp_process[ip_tag] = subprocess.Popen(command.split(" "))
        rtsp_count[ip_tag] = 1

    rtsp_time[ip_tag] = datetime.datetime.now() + datetime.timedelta(
        minutes=wait_time
    )
    return rtaddr


@app.route("/rtspToRtmpOff", methods=["GET"])
def rtsp_rtmp_off():
    ip = request.args.get("ip")
    ip_tag = get_ip_channel(ip) + "_rtmp"

    if ip_tag not in rtsp_process:
        return "-1"
    else:
        rtsp_count[ip_tag] -= 1
        if rtsp_count[ip_tag] <= 0:
            rtsp_process[ip_tag].kill()
            del rtsp_process[ip_tag]
            del rtsp_time[ip_tag]
            del rtsp_count[ip_tag]

    if ip_tag in rtsp_count:
        res = str(rtsp_count[ip_tag])
    else:
        res = "0"
    return res


@app.route("/rtspToRtmpContinue", methods=["GET"])
def rtsp_rtmp_continue():
    ip = request.args.get("ip")
    ip_tag = get_ip_channel(ip) + "_rtmp"

    if ip_tag not in rtsp_process:
        return "-1"
    else:
        rtsp_time[ip_tag] = datetime.datetime.now() + datetime.timedelta(
            minutes=wait_time
        )
    return str(rtsp_time[ip_tag])


def get_ip_channel(ip):
    return ip[ip.rindex("@") + 1 :].split("/")[0].replace(":", "_")


def close_by_time():
    def close():
        for ip_tag in list(rtsp_time.keys()):
            if rtsp_time[ip_tag] < datetime.datetime.now():
                rtsp_process[ip_tag].kill()
                del rtsp_process[ip_tag]
                del rtsp_time[ip_tag]
                del rtsp_count[ip_tag]

    schedule.every(2).minutes.do(close)
    while True:
        schedule.run_pending()


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=INNER_PORT)
    threading.Thread(target=close_by_time).start()